import db from './config/db.js';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function initDatabase() {
  let connection;
  try {
    console.log('开始初始化数据库...');
    
    // 读取SQL文件
    const sqlPath = path.join(__dirname, 'sql', 'create_user_table.sql');
    const sqlContent = await fs.readFile(sqlPath, 'utf-8');
    
    // 分割SQL语句
    const sqlStatements = sqlContent
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.length > 0);
    
    connection = await db.getConnection();
    
    // 执行每个SQL语句
    for (const sql of sqlStatements) {
      if (sql.trim()) {
        console.log('执行SQL:', sql.substring(0, 50) + '...');
        try {
          await new Promise((resolve, reject) => {
            connection.query(sql, (err, result) => {
              if (err) return reject(err);
              resolve(result);
            });
          });
        } catch (error) {
          // 如果是索引已存在的错误，忽略它
          if (error.code === 'ER_DUP_KEYNAME' || error.message.includes('Duplicate key name')) {
            console.log('索引已存在，跳过创建');
            continue;
          }
          throw error;
        }
      }
    }
    
    console.log('数据库初始化完成！');
    
    // 测试查询
    const testResult = await new Promise((resolve, reject) => {
      connection.query('SHOW TABLES LIKE "user"', (err, result) => {
        if (err) return reject(err);
        resolve(result);
      });
    });
    
    if (testResult.length > 0) {
      console.log('✅ user表创建成功');
    } else {
      console.log('❌ user表创建失败');
    }
    
  } catch (error) {
    console.error('数据库初始化失败:', error);
  } finally {
    if (connection) {
      connection.release();
    }
    process.exit(0);
  }
}

initDatabase();
